import Axios from "axios";
import http from "axios/lib/adapters/http.js";
import {stringify} from "querystring";

let ctoken = "";
const createRequest = async () => {
    let request = Axios.create({
        baseURL: "https://www.iconfont.cn",
        timeout: 10000,
        xsrfCookieName: "ctoken",
        xsrfHeaderName: "x-csrf-token",
        withCredentials: true,
        adapter: http,
    });
    let res = await request.get("/");
    let cookies = res.headers["set-cookie"] as Array<string>;
    let csrf: string;
    let cookie2 = "";
    if (cookies) {
        cookies.forEach((cookie) => {
            cookie2 += cookie.split(";")[0] + ";";
            if (cookie.includes("ctoken")) {
                csrf = cookie.match(/ctoken=(.*?);/)[1];
                ctoken = csrf;
            }
        });
    }
    request.defaults.headers = {
        cookie: cookie2,
        "x-csrf-token": csrf,
    };
    return request;
}

const params = (words: string[]): any => {
    let data: any = {
        page: 1,
        pageSize: 54,
        t: new Date().getTime(),
        q: words[0],
        sortType: "updated_at",
        ctoken: ctoken,
        fills: 0,//Setting.Get("color") - 0,
        sType: "",
        fromCollection: -1,
    };
    // if (Setting.Get("featured")) data[Setting.Get("featured")] = 1;
    // if (Setting.Get("type")) data[Setting.Get("type")] = 1;
    if (words.length >= 2) {
        words.forEach((word, index) => {
            if (index == 0) return;
            let keyParams = keywordParams[word];
            if (keyParams) data[keyParams.key] = keyParams.val;
        });
    }
    return data;
}

const cache = {
    items: [],
}

const search = async (keywords: string) => {
    let words = (keywords || "home").trim().split(/\s+/g);
    console.log('search', {keywords, words});
    const request = await createRequest();
    console.log('search.request', {
        params: params(words),
    });
    const r = await request.post(
        "api/icon/search.json",
        stringify(params(words)),
        {
            headers: {
                "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            },
        }
    );
    console.log('search.result', r.data);
    let icons = r.data.data.icons.map((icon: any) => {
        // if (Setting.Get("fill_color")) {
        //     icon.show_svg = icon.show_svg.replace(
        //         /fill="#.*?"/gim,
        //         `fill="${Setting.Get("fill_color")}"`
        //     );
        // }
        return {
            id: icon.id,
            icon: "data:image/svg+xml;utf8," + encodeURIComponent(icon.show_svg),
            title: icon.name.trim().replace(/\s+/g, "_"),
            description: "回车查看更多选项",
            data: icon.show_svg,
            keywords: keywords,
        };
    });
    return icons;
}

const defaultCode = {
    setting: {
        type: 'list',
        placeholder: '输入关键词搜索图标',
    },
    execute: async (item, keywords, data) => {
        if (item) {
            console.log('Iconfont execute', item, keywords, data);
            if (item.id.startsWith('Operate_')) {
                switch (item.id) {
                    case 'Operate_DownloadSvg':
                        let path = await focusany.showSaveDialog({
                            defaultPath: `${item.item.title}.svg`,
                            filters: {
                                extensions: ['svg']
                            }
                        })
                        if (!path) {
                            focusany.showToast('没有选择保存路径');
                            return null;
                        }
                        await focusany.file.write(path, item.item.data);
                        focusany.showToast(`文件已保存至:${path}`);
                        return {
                            command: 'close',
                        }
                    case 'Operate_Copy':
                        await focusany.showToast('复制成功');
                        await focusany.copyText(item.item.data);
                        return {
                            command: 'close'
                        }
                    case 'Operate_Back':
                        return {
                            command: 'data',
                            items: cache.items,
                        }
                }
            }
            if (item.id.startsWith('Icon_')) {
                const items = []
                items.push({
                    id: 'Operate_DownloadSvg',
                    icon: item.icon,
                    title: '下载SVG格式',
                    description: '下载图标到本地',
                    loading: false,
                    item: item,
                })
                items.push({
                    id: 'Operate_Copy',
                    icon: 'copy.svg',
                    title: '复制图标',
                    description: '复制图标到剪贴板',
                    loading: false,
                    item: item,
                })
                items.push({
                    id: 'Operate_Back',
                    icon: 'back.svg',
                    title: '返回搜索结果',
                    description: '复制图标到剪贴板',
                    loading: false,
                    item: item,
                })
                return {
                    command: "data",
                    items,
                }
            }
            return {
                command: "error",
                error: "未知操作",
            }
        }
        let items = await search(keywords);
        items = items.map((icon) => {
            return {
                ...icon,
                loading: false,
                id: `Icon_${icon.id}`,
            };
        })
        cache.items = items;
        return {
            command: "data",
            items,
        }
    }
}

window.exports = {
    code: {
        "default": defaultCode,
    }
}
